//
//  NSObject+RxSwift.swift
//  Pods
//
//  Created by Rdxer on 2017/8/15.
//
//

import Foundation
import RxSwift

public protocol JRDisposeBagOwner {
    var dispose:DisposeBag {get}
}

public extension Disposable {
    func disposed(by bag: JRDisposeBagOwner?) {
        if let bagdispose = bag?.dispose {
            disposed(by: bagdispose)
        }
    }
}

extension NSObject:JRDisposeBagOwner{
    
    public var dispose:DisposeBag {
        get {
            return djr.dispose
        }
    }

    public func resetDisposeBag(){
        objc_setAssociatedObject(self, &JRDisposableKey, DisposeBag.init(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}

private var JRDisposableKey: Void?
//private var JRDisposableKey_fixed_dispose: Void?
extension NSObject: DJRCompatible {}

public extension DJR where T: NSObject {
    fileprivate(set) var dispose:DisposeBag {
        get {
            guard let value = objc_getAssociatedObject(self.base, &JRDisposableKey) as? DisposeBag else {
                let obj = DisposeBag.init()
                objc_setAssociatedObject(self.base, &JRDisposableKey, obj, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return obj
            }
            return value
        }
        set {
            objc_setAssociatedObject(self.base, &JRDisposableKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
//    fileprivate(set) var fixed_dispose:DisposeBag {
//        get {
//            if let value = objc_getAssociatedObject(self.base, &JRDisposableKey_fixed_dispose) as? DisposeBag{
//                return value
//            }
//            return DisposeBag.init()
//        }
//        set {
//            objc_setAssociatedObject(self.base, &JRDisposableKey_fixed_dispose, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//        }
//    }
}
